<script setup lang="ts">
import type { UploadProps } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { upload } from "../services/upload";
const emit = defineEmits();
const props = defineProps<{ imageUrl: string | undefined }>();
const imageUrl = ref(props.imageUrl);
const Upload = (param) => {
  var formData = new FormData();
  formData.append("file", param.file);
  formData.append("filePath", "file/");
  upload(formData) 
    .then((res) => {
      imageUrl.value = res.data;
      emit("upload-success", res.data);
    })
    .catch((error) => {});
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("图片类型错误!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("图片不能超过10M");
    return false;
  }
  return true;
};
</script>

<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :http-request="Upload"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<style lang="less" scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>
